package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pogo.User;
import com.tanhua.server.pogo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class MovementsService {

    @Autowired
    private PicUploadService picUploadService;

//    @Reference(version = "1.0.0")
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发布动态
     * @param textContent
     * @param location
     * @param longitude
     * @param latitude
     * @param imageContents
     * @return
     */
    public Boolean saveMovements(String textContent,
                                 String location,
                                 String longitude,
                                 String latitude,
                                 MultipartFile[] imageContents) {
        //校验token
        User user = UserThreadLocal.get();

        //填充publish内容（动态内容）
        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLongitude(longitude);
        publish.setLatitude(latitude);

        //图片上传
        List<String> imageUrls = new ArrayList<>();
        for (MultipartFile file : imageContents) {
            PicUploadResult uploadResult = this.picUploadService.upload(file);
            imageUrls.add(uploadResult.getName());
        }
        publish.setMedias(imageUrls);

        return this.quanZiApi.savePublish(publish);

    }

    //查询动态,,公共部分
    private PageResult queryPublishList(User user,Integer page, Integer pageSize) {

        Long userId=null;//默认查询推荐动态

        if (user!=null){
            userId=user.getId();//查询好友动态
        }

        //默认pageResult
        PageResult pageResult = new PageResult();
        pageResult.setCounts(0);
        pageResult.setPages(0);
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);

        //获取publish
        PageInfo<Publish> pageInfo = this.quanZiApi.queryPublishList(userId, page, pageSize);
        List<Publish> records = pageInfo.getRecords();

        if (CollectionUtils.isEmpty(records)){
            //没有查到动态
            return pageResult;
        }

        //填充动态信息数据
        List<Movements> movementsList = fillValueToMovements(records);

        pageResult.setItems(movementsList);
        return pageResult;
    }

    //私有方法，公共部分 填充动态信息数据
    private List<Movements> fillValueToMovements(List<Publish> records){

        List<Movements> movementsList=new ArrayList<>();
        List<Long> userIds=new ArrayList<>();

        for (Publish record : records) {
            Movements movements = new Movements();

            //没有才添加
            if (!userIds.contains(record.getUserId())){
                userIds.add(record.getUserId());
            }

            //填充movement数据
            movements.setId(record.getId().toHexString());//动态id
            movements.setUserId(record.getUserId());

            //是否已点赞
            Long id = UserThreadLocal.get().getId();
            String userHasLikeKey= "QUANZI_COMMENT_LIKE_USER_"+id+"_"+movements.getId();
            movements.setHasLiked(this.redisTemplate.hasKey(userHasLikeKey)?1:0);

            //点赞数
            String likeCommentKey="QUANZI_COMMENT_LIKE_"+movements.getId();
            String likeCount=this.redisTemplate.opsForValue().get(likeCommentKey);
            if (StringUtils.isNotEmpty(likeCount)){
                movements.setLikeCount(Integer.valueOf(likeCount));
            }else {
                movements.setLikeCount(0);
            }

            //是否已经喜欢
//            Long id = UserThreadLocal.get().getId();
            String userHasLoveKey= "QUANZI_COMMENT_LOVE_USER_"+id+"_"+movements.getId();
            movements.setHasLoved(this.redisTemplate.hasKey(userHasLoveKey)?1:0);

            //喜欢数
            String loveCommentKey="QUANZI_COMMENT_LOVE_"+movements.getId();
            String loveCount=this.redisTemplate.opsForValue().get(loveCommentKey);
            if (StringUtils.isNotEmpty(loveCount)){
                movements.setLoveCount(Integer.valueOf(loveCount));
            }else {
                movements.setLoveCount(0);
            }


            //评论数
            Long commentCount = this.quanZiApi.queryCommentCount(movements.getId(), 2);
            movements.setCommentCount(commentCount.intValue());


            movements.setDistance("1.2公里");//// TODO: 2021/2/24 距离
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));//发布时间
            movements.setTextContent(record.getText());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));//动态图片

            movementsList.add(movements);
        }


        //查询数据库，好友信息
        QueryWrapper<UserInfo> userInfoQueryWrapper=new QueryWrapper<>();
        userInfoQueryWrapper.in("user_id",userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(userInfoQueryWrapper);

        //添加好友信息
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfoList) {
                if (movements.getUserId().longValue()== userInfo.getUserId().longValue()){

                    movements.setTags(StringUtils.split(userInfo.getTags(),","));
                    movements.setNickname(userInfo.getNickName());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setAge(userInfo.getAge());

                    break;
                }
            }
        }

        return movementsList;
    }

    //查询推荐动态
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(null,page,pageSize);
    }

    //查询好友动态
    public PageResult queryUserPublishList(Integer page, Integer pageSize) {

        return this.queryPublishList(UserThreadLocal.get(),page,pageSize);
    }

    //给动态点赞
    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();

        boolean b = this.quanZiApi.saveLikeComment(user.getId(), publishId);
        if (b==false){
            //保存失败
            return null;
        }
        //保存成功,获取点赞数
        Long likeCount=0l;
        String likeCommentKey="QUANZI_COMMENT_LIKE_"+publishId;
        if (!this.redisTemplate.hasKey(likeCommentKey)){
            //未缓存
               likeCount = this.quanZiApi.queryCommentCount(publishId, 1);
               this.redisTemplate.opsForValue().set(likeCommentKey,String.valueOf(likeCount));
        }else {
            //已有缓存
            likeCount = this.redisTemplate.opsForValue().increment(likeCommentKey);
        }

        //记录当前用户已经点赞
        String userHasLikeKey= "QUANZI_COMMENT_LIKE_USER_"+user.getId()+"_"+publishId;
        this.redisTemplate.opsForValue().set(userHasLikeKey,"1");

        return likeCount;
    }

    //取消动态点赞
    public Long dislikeComment(String publishId) {

        User user = UserThreadLocal.get();
        boolean b = this.quanZiApi.removeComment(user.getId(), publishId, 1);
        if (!b){
            //取消失败
            return null;
        }

        //取消点赞成功，redis中的点赞数要减去1
        String likeCommentKey="QUANZI_COMMENT_LIKE_"+publishId;
        Long count = this.redisTemplate.opsForValue().decrement(likeCommentKey);

        //删除该用户标记点赞
        String userHasLikeKey= "QUANZI_COMMENT_LIKE_USER_"+user.getId()+"_"+publishId;
        this.redisTemplate.delete(userHasLikeKey);

        return count;
    }

    //给动态喜欢
    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();

        boolean b = this.quanZiApi.saveLoveComment(user.getId(), publishId);
        if (!b){
            //保存失败
            return null;
        }
        //保存成功,获取喜欢数
        Long loveCount=0l;
        String loveCommentKey="QUANZI_COMMENT_LOVE_"+publishId;
        if (!this.redisTemplate.hasKey(loveCommentKey)){
            //未缓存
            loveCount = this.quanZiApi.queryCommentCount(publishId, 3);
            this.redisTemplate.opsForValue().set(loveCommentKey,String.valueOf(loveCount));
        }else {
            //已有缓存
            loveCount = this.redisTemplate.opsForValue().increment(loveCommentKey);
        }

        //记录当前用户已经点赞
        String userHasLikeKey= "QUANZI_COMMENT_LOVE_USER_"+user.getId()+"_"+publishId;
        this.redisTemplate.opsForValue().set(userHasLikeKey,"1");

        return loveCount;
    }

    //取消动态喜欢
    public Long unloveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean b = this.quanZiApi.removeComment(user.getId(), publishId, 3);
        if (!b){
            //取消失败
            return null;
        }

        //取消喜欢成功，redis中的点赞数要减去1
        String loveCommentKey="QUANZI_COMMENT_LOVE_"+publishId;
        Long count = this.redisTemplate.opsForValue().decrement(loveCommentKey);

        //删除该用户标记喜欢
        String userHasLoveKey= "QUANZI_COMMENT_LOVE_USER_"+user.getId()+"_"+publishId;
        this.redisTemplate.delete(userHasLoveKey);

        return count;
    }

    public Movements queryMovementsById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (null==publish){
            return null;
        }

        //根据查到数据，进行数据填充
        List<Movements> movementsList = this.fillValueToMovements(Arrays.asList(publish));
        return movementsList.get(0);
    }
}
